import User from './user'
import Order from './order'
import Helper from './helper'

import axios from 'axios'

const _axios = axios.create({
    baseURL: 'https://api.ysmove.com',
    timeout: 5000
})

export default {
    name: 'api',
    install(Vue, options) {
        const user = new User(_axios);
        const order = new Order(_axios);
        const router = options.router;

        Object.defineProperty(Vue.prototype, '$http', { value: _axios });
        Object.defineProperty(Vue.prototype, '$user', { value: user });
        Object.defineProperty(Vue.prototype, '$order', { value: order });
        Object.defineProperty(Vue.prototype, '$helper', {
            value : new Helper()
        });

        // Http请求拦截器
        _axios.interceptors.request.use(function (config) {
            // Do something before request is sent

            $('.loading-spinner').show();
            if (config.no_indicator) {
                //console.log('no_loading')
            }
            else {
                //Indicator.open()
                console.log('http request begin.');
            }

            return config
        }, function (error) {
            // Do something with request error
            return Promise.reject(error)
        })

        // 响应拦截器
        _axios.interceptors.response.use(
            response => {
                $('.loading-spinner').hide();
                //console.log('http request completed.')

                if (response.status === 200) {
                    var result = response.data;
                    if (!result.success && result.data.status == '401') {
                        localStorage.clear(); //清空本地信息

                        router.replace({
                            path: '/login',
                            query: { redirect: router.currentRoute.fullPath }
                        });

                        return Promise.reject(response);
                    }

                    return Promise.resolve(response);
                } else {
                    return Promise.reject(response);
                }
            },
            error => {
                $('.loading-spinner').hide();
                
                if (error.response == undefined) {
                    alert('Network error.')
                    return Promise.reject(error);
                };

                if (error.response.status) {
                    switch (error.response.status) {
                        // 401: 未登录                
                        // 未登录则跳转登录页面，并携带当前页面的路径                
                        // 在登录成功后返回当前页面，这一步需要在登录页操作。                
                        case 401:
                            router.replace({
                                path: '/login',
                                query: { redirect: router.currentRoute.fullPath }
                            });
                            break;
                        // 403 token过期                
                        // 登录过期对用户进行提示                
                        // 清除本地token和清空vuex中token对象                
                        // 跳转登录页面                
                        case 403:
                            Toast({
                                message: '登录过期，请重新登录',
                                duration: 1000,
                                forbidClick: true
                            });
                            // 清除token                    
                            localStorage.removeItem('token');
                            store.commit('loginSuccess', null);
                            // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
                            setTimeout(() => {
                                router.replace({
                                    path: '/login',
                                    query: {
                                        redirect: router.currentRoute.fullPath
                                    }
                                });
                            }, 1000);
                            break;
                        // 404请求不存在                
                        case 404:
                            Toast({
                                message: '网络请求不存在',
                                duration: 1500,
                                forbidClick: true
                            });
                            break;
                        // 其他错误，直接抛出错误提示                
                        default:
                            Toast({
                                message: error.response.data.message,
                                duration: 1500,
                                forbidClick: true
                            });
                    }
                    return Promise.reject(error.response);
                }
            }
        )
    }
}